import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import Actions from './qiankun/actions'

// 设置 webpack 公共路径
if (window.__POWERED_BY_QIANKUN__) {
  // 记得加双下划线 + 统一命名
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
}

let root = null;

// 修改：接收 props 并获取 container
function render(props = {}) {
  const { container } = props;
  const rootElement = container ? container.querySelector('#root') : document.getElementById('root');
  if (!rootElement) {
    throw new Error('Root element not found');
  }
  root = ReactDOM.createRoot(rootElement);
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
}

// 独立运行时直接渲染
if (!window.__POWERED_BY_QIANKUN__) {
  render();
}

// 导出生命周期函数
const lifecycles = {
  bootstrap: async () => {
  },
  mount: async (props) => {
    // 首先初始化 Actions
    if (props) {
      // 保存 qiankun 传递的通信方法
      const { onGlobalStateChange, setGlobalState, getGlobalState, offGlobalStateChange } = props;
      
      // 确保所有通信方法都有值后再设置
      if (onGlobalStateChange && setGlobalState) {
        const actions = {
          onGlobalStateChange,
          setGlobalState,
          getGlobalState: getGlobalState || (() => ({})),
          offGlobalStateChange: offGlobalStateChange || (() => {})
        };
        
        Actions.setActions(actions);
      } else {
        console.warn('[ReactApp] Missing required props for Actions initialization');
      }
    }
    
    // 然后渲染应用
    render(props);
  },
  unmount: async () => {
    root?.unmount();
    root = null;
  },
};

// 关键：将生命周期函数挂载到 window.ReactApp（名称需与主应用注册的 name 一致）
if (typeof window !== 'undefined') {
  window.ReactApp = lifecycles;
}
